//
//  RZChatSessionInputBarControl.m
//  RZIM
//
//  Created by reyzhang on 2021/8/4.
//

#import "RZChatSessionInputBarControl.h"
#import "RZKitUtility.h"
#import "RZIMDefine.h"
#import "UIManager.h"
#import "RZKitCommonDefine.h"
#import "RZVoiceRecordControl.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "RZVideoCaptureViewController.h"

//单个cell的高度是70（RCPlaginBoardCellSize）*2 + 上下padding的高度14*2 ＋
//上下两个图标之间的padding
#define Height_EmojBoardView 223.5f
#define Height_PluginBoardView 223.5f
#define Height_CommonPhrasesView 223.5f
#define CommonPhrasesView_Height 38

// 标准系统状态栏高度
#define SYS_STATUSBAR_HEIGHT 20
// 热门栏高度
#define HOTSPOT_STATUSBAR_HEIGHT 20
#define APP_STATUSBAR_HEIGHT (CGRectGetHeight([UIApplication sharedApplication].statusBarFrame))
// 根据APP_STATUSBAR_HEIGHT判断是不是存在热门栏
#define IS_HOTSPOT_CONNECTED (APP_STATUSBAR_HEIGHT == (SYS_STATUSBAR_HEIGHT + HOTSPOT_STATUSBAR_HEIGHT) ? YES : NO)

#define SwitchButtonWidth 44



@interface RZChatSessionInputBarControl () <RZInputContainerViewDelegate,RZEmojiViewDelegate,RZPluginBoardViewDelegate,RZVoiceRecordControlDelegate>
@property (nonatomic) CGRect keyboardFrame;
@property (nonatomic) BOOL isContainViewAppeared;
@property (nonatomic) int isNew;

@property (nonatomic, strong) RZVoiceRecordControl *voiceRecordControl;

@end

@implementation RZChatSessionInputBarControl

- (instancetype)initWithFrame:(CGRect)frame
            withContainerView:(UIView *)containerView
             defaultInputType:(RZChatSessionInputBarInputType)defaultInputType {
    self = [super initWithFrame:frame];
    if (self) {
        _containerView = containerView;
        [self commonInit];
        [self setDefaultInputType:defaultInputType];
    }
    return self;
}


- (void)commonInit {
    self.backgroundColor = [UIColor colorWithRed:245/255.0 green:246/255.0 blue:249/255.0 alpha:1];
    self.keyboardFrame = CGRectZero;
    self.isNew = 0;
    
    [self setupSubViews];
}


- (void)setupSubViews {
    [self addSubview:self.inputContainerView];
    [self addBottomAreaView];
}

- (void)addBottomAreaView {
    CGFloat bottom = kSafeAreaBottom;
    if (bottom > 0) {
        UIView * bottomAreaView= [[UIView alloc] initWithFrame:CGRectMake(0, self.containerView.bounds.size.height - bottom - 64 - kSafeAreaTop,
                                                                          self.containerView.bounds.size.width, bottom)];
        bottomAreaView.backgroundColor = [UIColor colorWithRed:246/255.0 green:246/255.0 blue:246/255.0 alpha:1];
        [self.containerView addSubview:bottomAreaView];
    }
}


#pragma mark - Super Methods
- (void)setFrame:(CGRect)frame{
    [super setFrame:frame];
    if ([self.delegate respondsToSelector:@selector(chatInputBar:shouldChangeFrame:)]) {
        [self.delegate chatInputBar:self shouldChangeFrame:frame];
    }
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    //上边线
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, self.frame.size.width, 0.5);
    layer.backgroundColor = [UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1].CGColor;
    [self.layer addSublayer:layer];
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

//隐藏系统默认的菜单项
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    return NO; //隐藏系统默认的菜单项
}


- (void)changeTextViewHeight:(NSString *)text {
    //如果文本框中还保留文本，则进来显示为键盘模式
    if (text.length != 0) {
        [self animationLayoutBottomBarWithStatus:(KBottomBarKeyboardStatus) animated:YES];
    }
}



- (void)containerViewWillAppear {
    self.isContainViewAppeared = YES;
    [self inputBar_registerForNotifications]; //注册通知，监听键盘
    
    //设置初始时的显示模式
    if (_isNew == 0) { //默认模式
        [self animationLayoutBottomBarWithStatus:KBottomBarDefaultStatus animated:NO];
    }
    
    //键盘弹出模式
    if (self.currentBottomBarStatus == KBottomBarKeyboardStatus) {
        [self animationLayoutBottomBarWithStatus:KBottomBarKeyboardStatus animated:NO];
    }
}

- (void)containerViewDidAppear {
    if (self.inputTextView.text && self.inputTextView.text.length > 0 &&
        (self.currentBottomBarStatus == KBottomBarKeyboardStatus ||
         (self.currentBottomBarStatus == KBottomBarDefaultStatus && _isNew == 0) ||
         self.currentBottomBarStatus == KBottomBarDestructStatus)) {
        [self changeTextViewHeight:self.inputTextView.text];
    }
    _isNew = 1;
}

- (void)containerViewWillDisappear {
    self.isContainViewAppeared = NO;
    [self inputBar_unregisterForNotifications];
}

- (void)containerViewSizeChangedNoAnnimation {
    [self animationLayoutBottomBarWithStatus:self.currentBottomBarStatus animated:NO];
}

- (void)containerViewSizeChanged {
    [self animationLayoutBottomBarWithStatus:self.currentBottomBarStatus animated:YES];
}

- (void)updateStatus:(KBottomBarStatus)inputBarStatus animated:(BOOL)animated {
    [self animationLayoutBottomBarWithStatus:inputBarStatus animated:animated];
}

- (void)resetToDefaultStatus {
    if (self.currentBottomBarStatus != KBottomBarDefaultStatus) {
        [self animationLayoutBottomBarWithStatus:KBottomBarDefaultStatus animated:YES];
    }
}

- (void)setDefaultInputType:(RZChatSessionInputBarInputType)defaultInputType {
    if (defaultInputType == RCChatSessionInputBarInputVoice) {
        [self animationLayoutBottomBarWithStatus:KBottomBarRecordStatus animated:YES];
    } else if (defaultInputType == RCChatSessionInputBarInputExtention) {
        [self animationLayoutBottomBarWithStatus:KBottomBarPluginStatus animated:YES];
    } else if (defaultInputType == RCChatSessionInputBarInputDestructMode) {
        [self resetToDefaultStatus];
        [self animationLayoutBottomBarWithStatus:KBottomBarDestructStatus animated:YES];
    }
}


#pragma mark - Notifications

- (void)inputBar_registerForNotifications {
    [self inputBar_unregisterForNotifications];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(inputBar_didReceiveKeyboardWillShowNotification:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(inputBar_didReceiveKeyboardWillHideNotification:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didChangeDeviceOrientationNotification:)
                                                 name:UIApplicationDidChangeStatusBarOrientationNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didCreateNewSession)
                                                 name:@"RCCallNewSessionCreation Notification"
                                               object:nil];
}

- (void)didChangeDeviceOrientationNotification:(NSNotification *)notification {
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    if (orientation == UIDeviceOrientationPortrait) {
        [self animationLayoutBottomBarWithStatus:self.currentBottomBarStatus animated:YES];
    }
}

- (void)inputBar_unregisterForNotifications {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)inputBar_didReceiveKeyboardWillShowNotification:(NSNotification *)notification {
    NSLog(@"%s", __FUNCTION__);
    //textViewBeginEditing 是在 inputTextView 代理 textViewShouldBeginEditing 中赋值
    //此判断是避免会话页面其他输入框的响应导致会话输入框弹起
    if (self.inputContainerView.textViewBeginEditing) {
        NSDictionary *userInfo = [notification userInfo];
        CGRect keyboardBeginFrame = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
        CGRect keyboardEndFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        if (!CGRectEqualToRect(keyboardBeginFrame, keyboardEndFrame)) {
            UIViewAnimationCurve animationCurve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
            NSInteger animationCurveOption = (animationCurve << 16);
            
            double animationDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
            [UIView animateWithDuration:animationDuration delay:0.0 options:animationCurveOption animations:^{
                self.keyboardFrame = keyboardEndFrame;
                [self animationLayoutBottomBarWithStatus:KBottomBarKeyboardStatus animated:NO];
            }completion:^(BOOL finished){
                
            }];
        }
    }else{
        //部分情况键盘弹起会先发通知再走 textViewShouldBeginEditing， 如摇动手机撤回输入内容
        __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (weakSelf.inputContainerView.textViewBeginEditing) {
                [weakSelf inputBar_didReceiveKeyboardWillShowNotification:notification];
            }
        });
    }
    if (@available(iOS 13.0, *)) {
        [[UIMenuController sharedMenuController] hideMenuFromView:self];
    } else {
        [[UIMenuController sharedMenuController] setMenuItems:nil];
        [UIMenuController sharedMenuController].menuVisible = NO;
    }
}

- (void)inputBar_didReceiveKeyboardWillHideNotification:(NSNotification *)notification {
    NSLog(@"%s", __FUNCTION__);
    if (self.currentBottomBarStatus == KBottomBarKeyboardStatus) {
        [self animationLayoutBottomBarWithStatus:KBottomBarDefaultStatus animated:NO];
    }
}

- (void)didCreateNewSession {
//    [self endVoiceRecord];
}



#pragma mark Public method
// 打开相册
- (void)openSystemAlbum {

    TZImagePickerController *pickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:0 delegate:nil];
    pickerVC.naviBgColor = [UIColor whiteColor];
    pickerVC.naviTitleColor = RGBCOLOR(51, 51, 51);
    pickerVC.barItemTextColor = RGBCOLOR(51, 51, 51);
    pickerVC.doneBtnTitleStr = @"确定";
    pickerVC.cancelBtnTitleStr = @"取消";
    pickerVC.allowPickingVideo = NO;
//    pickerVC.iconThemeColor = MainColor;
    pickerVC.modalPresentationStyle = UIModalPresentationFullScreen;
    
    pickerVC.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if ([self.delegate respondsToSelector:@selector(imageDataDidSelect:fullImageRequired:)]) {
            [self.delegate imageDataDidSelect:photos fullImageRequired:isSelectOriginalPhoto];
        }
    };
    [self.delegate presentViewController:pickerVC functionTag:PLUGIN_BOARD_ITEM_ALBUM_TAG];
}
//
// 打开相机
- (void)openSystemCamera {
    if ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] == AVAuthorizationStatusNotDetermined) {
        [self requestCameraAccess:^(BOOL granted) {
            if (granted) {
                [self startCamera];
            } else {
                [self checkAndAlertCameraAccessRight];
            }
        }];
    } else {
        if ([self checkAndAlertCameraAccessRight]) {
            [self startCamera];
        }
    }
}

- (void)requestCameraAccess:(void (^)(BOOL granted))handler {
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
                             completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                handler(YES);
            } else {
                handler(NO);
            }
        });
    }];
}


- (void)startCamera {
    
    RZVideoCaptureViewController *vc = [RZVideoCaptureViewController sharedVideoVC];
    vc.takeBlock = ^(SelectMediaType type, id item) {
        if ([self.delegate respondsToSelector:@selector(sightDidFinishRecord:thumbnail:duration:)]) {
            if (type == SelectMediaTypePhoto) {
                [self.delegate sightDidFinishRecord:@"" thumbnail:item duration:0];
            }else {
                if ([item isKindOfClass:[NSURL class]]) {
                    
                    PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[item] options:nil];
                    PHAsset *asset = result.firstObject;
                    if (asset) {
                        [self handlerVideoWithAsset:asset];
                    }
                }
                
            }
        }
    };
    [self.delegate presentViewController:vc functionTag:PLUGIN_BOARD_ITEM_CAMERA_TAG];
}


- (BOOL)checkAndAlertCameraAccessRight {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied || authStatus == AVAuthorizationStatusRestricted) {
        [RZKitUtility showAlertWithTitle:@"" message:@"访问相机未授权" from:self showCancel:NO confirmHandler:^{
            
        }];
        return NO;
    }
    return YES;
}


- (void)handlerVideoWithAsset:(PHAsset *)asset {
    
    //1. 先获取具体的文件地址
    [RZKitUtility getURlByAsset:asset success:^(NSURL * _Nonnull videoUrl) {
       
        NSLog(@"原 video url:%@",videoUrl);
        //2. 对原视频进行压缩
        [RZKitUtility videoPressWithOrginUrl:videoUrl success:^(NSURL * _Nonnull finalUrl) {
           
            NSLog(@"压缩后的 final video url:%@",finalUrl);
            
            //3.拿取视频第一帧
            UIImage *image = [RZKitUtility getVideoPreViewImage:finalUrl];
            
            if ([self.delegate respondsToSelector:@selector(sightDidFinishRecord:thumbnail:duration:)]) {
                [self.delegate sightDidFinishRecord:[finalUrl path] thumbnail:image duration:asset.duration];
            }
            
            
        }];
        
    }];
}


- (void)cancelVoiceRecord {
    [self.voiceRecordControl onCancelRecordEvent];
}

- (void)endVoiceRecord {
    [self.voiceRecordControl onEndRecordEvent];
}

#pragma mark 控制ChatToolBar的位置显示
/**
 重要：状态切换，位置变化
 */
- (void)animationLayoutBottomBarWithStatus:(KBottomBarStatus)bottomBarStatus animated:(BOOL)animated {
    
    //知识点：当处理的动画逻辑比较多时，建议使用UIView 的beginAnimations + commitAnimations. 不建议使用block的方式
    if (animated == YES) {
        [UIView beginAnimations:@"Move_bar" context:nil];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        [UIView setAnimationDuration:0.25f];
        [UIView setAnimationDelegate:self];
        [self layoutBottomBarWithStatus:bottomBarStatus];
        [UIView commitAnimations];
    } else {
        [self layoutBottomBarWithStatus:bottomBarStatus];
    }
}


- (void)layoutBottomBarWithStatus:(KBottomBarStatus)bottomBarStatus {
    
    //根据barstatus 改变容器的子控件显示状态
    [self.inputContainerView setBottomBarWithStatus:bottomBarStatus];
    
    
    CGRect chatInputBarRect = self.frame; //读取当前位置，留用
    float bottomY = [self getBoardViewBottomOriginY]; //读取面板view的bottom,留用
    
    //根据状态，控制显示聊天工具条，在父视图中的显示位置
    switch (bottomBarStatus) {
        case KBottomBarDefaultStatus: {
            [self hiddenEmojiBoardView:YES pluginBoardView:YES];
            chatInputBarRect.origin.y = bottomY - self.bounds.size.height; //调整当前控件的y坐标
        } break;
        case KBottomBarKeyboardStatus: {
            [self hiddenEmojiBoardView:YES pluginBoardView:YES];
            //bottomY里面已经去掉了屏幕底部安全距离
            if (self.keyboardFrame.size.height > 0) {
                //手机系统键盘弹起时，键盘的高度也包含了屏幕底部安全距离，相当于减掉了两次屏幕底部安全距离，需要再加回去
                chatInputBarRect.origin.y = bottomY - self.bounds.size.height - self.keyboardFrame.size.height + [self getSafeAreaExtraBottomHeight];
            }else{
               //使用外接键盘时手机系统键盘并未弹起
                chatInputBarRect.origin.y = bottomY - self.bounds.size.height;
            }
        } break;
        case KBottomBarPluginStatus: {
            [self pluginBoardView];
            [self hiddenEmojiBoardView:YES pluginBoardView:NO];
            chatInputBarRect.origin.y = bottomY - self.bounds.size.height - self.pluginBoardView.bounds.size.height;
        } break;
        case KBottomBarEmojiStatus: {
            [self emojiBoardView];
            [self hiddenEmojiBoardView:NO pluginBoardView:YES];
            chatInputBarRect.origin.y = bottomY - self.bounds.size.height - self.emojiBoardView.bounds.size.height;
        } break;
        case KBottomBarRecordStatus: {
            [self hiddenEmojiBoardView:YES pluginBoardView:YES];
            chatInputBarRect.origin.y = bottomY - self.bounds.size.height;
        } break;
        default:
            break;
    }
    [self setFrame:chatInputBarRect];
    
}


- (float)getBoardViewBottomOriginY {
    float gap = 64 + kSafeAreaTop;
    gap += kSafeAreaBottom;
    
    return [UIScreen mainScreen].bounds.size.height - gap;
}

- (float)getSafeAreaExtraBottomHeight {
    return [RZKitUtility getWindowSafeAreaInsets].bottom;
}

/**
 表情面板，控件面板控制
 */
- (void)hiddenEmojiBoardView:(BOOL)hiddenEmojiBoardView
             pluginBoardView:(BOOL)hiddenPluginBoardView {
    if (self.emojiBoardView) {
        [self.emojiBoardView setHidden:hiddenEmojiBoardView];
        if (!hiddenEmojiBoardView) {
            self.emojiBoardView.frame = CGRectMake(0, [self getBoardViewBottomOriginY] - Height_EmojBoardView, self.containerView.bounds.size.width, Height_EmojBoardView);
        }
    }
    if (self.pluginBoardView) {
        [self.pluginBoardView setHidden:hiddenPluginBoardView];
        if (!hiddenPluginBoardView) {
            self.pluginBoardView.frame = CGRectMake(0, [self getBoardViewBottomOriginY] - Height_PluginBoardView,
                                                    self.containerView.bounds.size.width, Height_PluginBoardView);
        }
    }
    
}


#pragma mark - RZInputContainerViewDelegate

//语音与键盘模式的切换
- (void)inputContainerViewSwitchButtonClicked:(RZInputContainerView *)inputContainerView {
    if (self.currentBottomBarStatus == KBottomBarRecordStatus) {
        [self animationLayoutBottomBarWithStatus:KBottomBarKeyboardStatus animated:YES];
    } else {
        [self animationLayoutBottomBarWithStatus:KBottomBarRecordStatus animated:YES];
    }
}

//表情面板切换显示
- (void)inputContainerViewEmojiButtonClicked:(RZInputContainerView *)inputContainerView {
    if (self.destructMessageMode) {
//        [self openDestructAlbum];
        return;
    }
    if (self.currentBottomBarStatus == KBottomBarEmojiStatus) {
        [self animationLayoutBottomBarWithStatus:KBottomBarKeyboardStatus animated:YES];
    } else {
        [self animationLayoutBottomBarWithStatus:KBottomBarEmojiStatus animated:YES];
    }
    [self enableEmojiBoardViewSendButton];
}

/**
 插件面板切换显示
 */
- (void)inputContainerViewAdditionalButtonClicked:(RZInputContainerView *)inputContainerView {
    if (self.destructMessageMode) {
        [self animationLayoutBottomBarWithStatus:KBottomBarDefaultStatus animated:YES];
        return;
    }
    if (self.currentBottomBarStatus == KBottomBarPluginStatus) {
        [self animationLayoutBottomBarWithStatus:KBottomBarKeyboardStatus animated:YES];
    } else {
        [self animationLayoutBottomBarWithStatus:KBottomBarPluginStatus animated:YES];
    }
}


/**
 语音录制按钮的各状态事件的处理
 */
- (void)inputContainerView:(RZInputContainerView *)inputContainerView forControlEvents:(UIControlEvents)controlEvents {
    [self didTouchRecordButtonEvent:controlEvents];
}

- (void)inputContainerView:(RZInputContainerView *)inputContainerView didChangeFrame:(CGRect)frame {
    CGRect vRect = self.frame;
    vRect.size.height = frame.size.height;
    vRect.origin.y += self.frame.size.height - vRect.size.height;
    self.frame = vRect;
}

- (BOOL)inputTextView:(UITextView *)inputTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([self.delegate respondsToSelector:@selector(inputTextView:shouldChangeTextInRange:replacementText:)]) {
        [self.delegate inputTextView:inputTextView shouldChangeTextInRange:range replacementText:text];
    }

    if ([text isEqualToString:@"\n"]) {
        if ([self.delegate respondsToSelector:@selector(inputTextViewDidTouchSendKey:)]) {
            NSString *formatString =
                [inputTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            if (formatString.length > 0) {
                [self.delegate inputTextViewDidTouchSendKey:inputTextView];
            }
        }
        NSLog(@"Enter key call inputTextViewDidChange");
        return NO;
    }
    return YES;
}


#pragma mark -  RZEmojiViewDelegate
- (void)didTouchEmojiView:(RZEmojiBoardView *)emojiView touchedEmoji:(NSString *)string {
    if (nil == string) {
        [self.inputTextView deleteBackward];
        NSRange range = NSMakeRange(self.inputTextView.selectedRange.location, string.length);
        if (self.delegate &&
            [self.delegate respondsToSelector:@selector(inputTextView:shouldChangeTextInRange:replacementText:)]) {
            [self.delegate inputTextView:self.inputTextView shouldChangeTextInRange:range replacementText:string];
        }
    } else {
        NSString *replaceString = string;
        if (replaceString.length < 5000) {
            NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:replaceString];
            [attStr addAttribute:NSFontAttributeName
                           value:self.inputTextView.font
                           range:NSMakeRange(0, replaceString.length)];
            [attStr addAttribute:NSForegroundColorAttributeName
                           value:[UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1]
                           range:NSMakeRange(0, replaceString.length)];
            NSInteger cursorPosition;
            if (self.inputTextView.selectedTextRange) {
                cursorPosition = self.inputTextView.selectedRange.location;
            } else {
                cursorPosition = 0;
            }
            //获取光标位置
            if (cursorPosition > self.inputTextView.textStorage.length)
                cursorPosition = self.inputTextView.textStorage.length;
            [self.inputTextView.textStorage insertAttributedString:attStr atIndex:cursorPosition];
            //输入表情触发文本框变化，更新@信息的range
            if ([self.inputTextView.delegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)]) {
                [self.inputTextView.delegate textView:self.inputTextView shouldChangeTextInRange:self.inputTextView.selectedRange replacementText:string];
            }
            
            NSRange range;
            range.location = self.inputTextView.selectedRange.location + string.length;
            range.length = 0;
            self.inputTextView.selectedRange = range;
        }
    }
    
    UITextView *textView = self.inputTextView;
    CGRect line = [textView caretRectForPosition:textView.selectedTextRange.start];
    CGFloat overflow =
    line.origin.y + line.size.height - (textView.contentOffset.y + textView.bounds.size.height -
                                        textView.contentInset.bottom - textView.contentInset.top);
    if (overflow > 0) {
        // We are at the bottom of the visible text and introduced a line feed,
        // scroll down (iOS 7 does not do it)
        // Scroll caret to visible area
        CGPoint offset = textView.contentOffset;
        offset.y += overflow + 7; // leave 7 pixels margin
        // Cannot animate with setContentOffset:animated: or caret will not appear
        __weak typeof(textView) weakTextView = textView;
        [UIView animateWithDuration:.2
                         animations:^{
            [weakTextView setContentOffset:offset];
        }];
    }
    [self enableEmojiBoardViewSendButton];
   
    if ([self.delegate respondsToSelector:@selector(emojiView:didTouchedEmoji:)]) {
        [self.delegate emojiView:emojiView didTouchedEmoji:string];
    }
}

- (void)didSendButtonEvent:(RZEmojiBoardView *)emojiView sendButton:(UIButton *)sendButton {
    NSString *_sendText = self.inputTextView.text;

    NSString *_formatString = [_sendText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    if (0 == [_formatString length]) {
//        [self showAlertController:nil
//                          message:RCLocalizedString(@"whiteSpaceMessage")
//                      cancelTitle:RCLocalizedString(@"OK")];
        return;
    }
    if ([self.delegate respondsToSelector:@selector(emojiView:didTouchSendButton:)]) {
        [self.delegate emojiView:emojiView didTouchSendButton:sendButton];
    }

    self.inputTextView.text = @"";
    [self enableEmojiBoardViewSendButton];
}


#pragma mark - RZPluginBoardViewDelegate
- (void)pluginBoardView:(RZPluginBoardView *)pluginBoardView clickedItemWithTag:(NSInteger)tag {
    if ([self.delegate respondsToSelector:@selector(pluginBoardView:clickedItemWithTag:)]) {
        [self.delegate pluginBoardView:pluginBoardView clickedItemWithTag:tag];
    }
}

#pragma mark - RZVoiceRecordViewDelegate
- (BOOL)recordWillBegin{
    if ([self.delegate respondsToSelector:@selector(recordWillBegin)]) {
        NSLog(@"recordWillBegin:==============> %d", [self.delegate recordWillBegin]);
        return [self.delegate recordWillBegin];
    }
    return YES;
}

- (void)voiceRecordControlDidBegin:(RZVoiceRecordControl *)voiceRecordControl {
    if ([self.delegate respondsToSelector:@selector(recordDidBegin)]) {
        [self.delegate recordDidBegin];
    }
}

- (void)voiceRecordControlDidCancel:(RZVoiceRecordControl *)voiceRecordControl {
    if ([self.delegate respondsToSelector:@selector(recordDidCancel)]) {
        [self.delegate recordDidCancel];
    }
}

- (void)voiceRecordControl:(RZVoiceRecordControl *)voiceRecordControl
                    didEnd:(NSData *)recordData
            recordFile:(NSURL *)recordFile
                  duration:(long)duration
                     error:(NSError *)error {
    if ([self.delegate respondsToSelector:@selector(recordDidEnd:recordFile:duration:error:)]) {
        [self.delegate recordDidEnd:recordData recordFile:recordFile duration:duration error:[NSError new]];
    }
}



#pragma mark - Private Method
/**
 语音录制按钮的各状态事件的处理
 */
- (void)didTouchRecordButtonEvent:(UIControlEvents)event {
    switch (event) {
    case UIControlEventTouchDown: {
        [self.voiceRecordControl onBeginRecordEvent];
    } break;
    case UIControlEventTouchUpInside: {
        [self.voiceRecordControl onEndRecordEvent];
    } break;
    case UIControlEventTouchDragExit: {
        [self.voiceRecordControl dragExitRecordEvent];
    } break;
    case UIControlEventTouchUpOutside: {
        [self.voiceRecordControl onCancelRecordEvent];

    } break;
    case UIControlEventTouchDragEnter: {
        [self.voiceRecordControl dragEnterRecordEvent];
    } break;
    case UIControlEventTouchCancel: {
        [self.voiceRecordControl onEndRecordEvent];
    } break;
    default:
        break;
    }
}

- (void)enableEmojiBoardViewSendButton{
    if (self.inputTextView.text && self.inputTextView.text.length > 0) {
           [self.emojiBoardView enableSendButton:YES];
       } else {
           [self.emojiBoardView enableSendButton:NO];
       }
}

- (void)showAlertController:(NSString *)title message:(NSString *)message cancelTitle:(NSString *)cancelTitle {
    dispatch_async(dispatch_get_main_queue(), ^{
        //TODO: Alert Show
    });
}

#pragma mark - Getters and Setters

- (RZInputContainerView *)inputContainerView {
    if (!_inputContainerView) {
        _inputContainerView = [[RZInputContainerView alloc] initWithFrame:self.bounds];
        _inputContainerView.delegate = self;
    }
    return _inputContainerView;
}

- (UIButton *)switchButton {
    return self.inputContainerView.switchButton;
}

- (UITextView *)inputTextView {
    return self.inputContainerView.inputTextView;
}

- (UIButton *)recordButton {
    return self.inputContainerView.recordButton;
}

- (UIButton *)emojiButton {
    return self.inputContainerView.emojiButton;
}

- (UIButton *)additionalButton {
    return self.inputContainerView.additionalButton;
}

- (BOOL)destructMessageMode {
    return self.inputContainerView.destructMessageMode;
}

- (void)setCurrentBottomBarStatus:(KBottomBarStatus)currentBottomBarStatus {
    self.inputContainerView.currentBottomBarStatus = currentBottomBarStatus;
}

- (KBottomBarStatus)currentBottomBarStatus {
    return self.inputContainerView.currentBottomBarStatus;
}

- (NSInteger)maxInputLines {
    return self.inputContainerView.maxInputLines;
}


- (RZEmojiBoardView *)emojiBoardView {
    if (!_emojiBoardView) {
        _emojiBoardView = [[RZEmojiBoardView alloc]
            initWithFrame:CGRectMake(0, [self getBoardViewBottomOriginY], self.frame.size.width, Height_EmojBoardView)
                 delegate:self];
        _emojiBoardView.hidden = YES;
        _emojiBoardView.delegate = self;
        [self.containerView addSubview:_emojiBoardView]; //被添加到容器控件 reyzhang
    }
    return _emojiBoardView;
}


- (RZPluginBoardView *)pluginBoardView {
    if (!_pluginBoardView) {
        _pluginBoardView = [[RZPluginBoardView alloc]
            initWithFrame:CGRectMake(0, [self getBoardViewBottomOriginY], self.containerView.bounds.size.width,
                                     Height_PluginBoardView)];

        //添加底部多功能栏功能，可以根据需求自定义
        [_pluginBoardView insertItem:RZResourceImage(@"plugin_item_picture")
                    highlightedImage:RZResourceImage(@"plugin_item_picture_highlighted")
                               title:@"照片"
                             atIndex:0
                                 tag:PLUGIN_BOARD_ITEM_ALBUM_TAG];
        
        [_pluginBoardView insertItem:RZResourceImage(@"plugin_item_camera")
                    highlightedImage:RZResourceImage(@"plugin_item_camera_highlighted")
                               title:@"拍摄"
                             atIndex:1
                                 tag:PLUGIN_BOARD_ITEM_CAMERA_TAG];
        
        _pluginBoardView.hidden = YES;
        _pluginBoardView.pluginBoardDelegate = self;
        [self.containerView addSubview:_pluginBoardView];
    }
    return _pluginBoardView;
}


- (RZVoiceRecordControl *)voiceRecordControl {
    if (!_voiceRecordControl) {
        _voiceRecordControl = [[RZVoiceRecordControl alloc] init];
        _voiceRecordControl.delegate = self;
    }
    return _voiceRecordControl;
}

@end
